package 栈;

import java.util.LinkedList;
import java.util.Queue;

/**
 * <p>
 * https://leetcode-cn.com/problems/implement-stack-using-queues/
 * 使用队列实现栈的下列操作：
 * push(x) -- 元素 x 入栈
 * pop() -- 移除栈顶元素
 * top() -- 获取栈顶元素
 * empty() -- 返回栈是否为空
 * </p>
 *
 * @author AJun
 * @since 2020/8/13
 */
public class _225_用队列实现栈 {

    private final Queue<Integer> queue;

    /**
     * Initialize your data structure here.
     */
    public _225_用队列实现栈() {
        queue = new LinkedList<>();
    }

    /**
     * Push element x onto stack.
     */
    public void push(int x) {
        queue.add(x);
        int size = queue.size();
        while (size > 1) { // 元素超过一个
            queue.offer(queue.poll());
            size--;
        }
    }

    /**
     * Removes the element on top of the stack and returns that element.
     */
    public int pop() {
        return queue.poll();
    }

    /**
     * Get the top element.
     */
    public int top() {
        return queue.peek();
    }

    /**
     * Returns whether the stack is empty.
     */
    public boolean empty() {
        return queue.isEmpty();
    }

}
